#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
import django.newforms as forms

from django.shortcuts import render_to_response
from django.template import Context, loader
from PhotoBlog.Post.models import PhotoPost
from datetime import datetime, date
from django.conf import settings
import os, Image
import StringIO

def index(request):
   """vue principal"""
   pass


def upload(request):
   """docstring for upload"""
   
   blogform = forms.form_for_model(PhotoPost)

   if (request.POST):
      bloghtml = blogform(request.POST)  
      new_data = request.POST.copy()  
      new_data.update(request.FILES)  
      bloghtml = blogform(new_data)  

      if bloghtml.is_valid():
         photo = Image.open(StringIO.StringIO(request.FILES['photo']['content']))
         photopath = '%simages/%s/' %(settings.MEDIA_ROOT, date.today().strftime('%Y-%m-%d'))
         if not os.access(photopath, os.F_OK):
            os.mkdir(photopath)
         photoname = request.FILES['photo']['filename']
         photo.save(photopath + photoname, 'jpeg')
         bloghtml.save()
   else:      
      blogform.base_fields['photo'].widget = forms.FileInput()
      blogform.base_fields['pub_date'].initial = str(datetime.now())
      blogform.base_fields['post_date'].initial = str(datetime.now())
      bloghtml = blogform()
   
   context = Context({'form': bloghtml.as_p()})
   return render_to_response('upload.html', context)
